from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from utils.mongo_client import MongoClientManager
from datetime import datetime, timedelta
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from utils.authentication import CustomJWTAuthentication

class CheckinView(APIView):
    authentication_classes = [CustomJWTAuthentication]
    permission_classes = [IsAuthenticated]

    @method_decorator(csrf_exempt)
    def post(self, request):
        """用户今日打卡"""
        user_id = request.user.id
        note = request.data.get("note", "")
        today = datetime.now().strftime("%Y-%m-%d")
        client = MongoClientManager.get_client()
        db = client['keep']
        collection = db['checkins']
        # 检查今天是否已打卡
        if collection.find_one({"user_id": user_id, "date": today}):
            return Response({"msg": "今日已打卡"}, status=400)
        doc = {
            "user_id": user_id,
            "date": today,
            "note": note,
            "created_at": datetime.now()
        }
        collection.insert_one(doc)
        return Response({"msg": "打卡成功"})

    def get(self, request):
        """获取打卡历史和连续天数（优化：无论今天是否打卡，都能显示最近一次连续打卡的天数）"""
        user_id = request.user.id
        client = MongoClientManager.get_client()
        db = client['keep']
        collection = db['checkins']
        records = list(collection.find({"user_id": user_id}).sort("date", -1))
        for r in records:
            r["_id"] = str(r["_id"])
        # 优化 streak 统计逻辑
        dates = sorted([datetime.strptime(r["date"], "%Y-%m-%d").date() for r in records], reverse=True)
        streak = 0
        if dates:
            streak = 1
            for i in range(1, len(dates)):
                if (dates[i-1] - dates[i]).days == 1:
                    streak += 1
                else:
                    break
        return Response({"records": records, "streak": streak}) 